import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { environment } from '../../../../environments/environment';
import { DatePipe } from '@angular/common';
import { StatusFollowService } from '@core/statusFollow.service';
import { forkJoin } from 'rxjs';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { ApiService } from '@core/api.service';
import { LocalStorage } from '@core/local.storage';
import { ExportFileService } from '@core/exportFile';

@Component({
    selector: 'app-sxdaqkk-detail',
    templateUrl: './sxdaqkk_detail.component.html',
    styleUrls: ['./sxdaqkk_detail.component.less']
})

export class SxdaqkkDetailComponent implements OnInit {
    queryParam: any = {};
    tableData = []
    pageType: any;
    pageSize = '20';
    pageTotal = 0;
    pageIndex = 1;
    _params;
    tabIndex = 0;
    tableHeight = window.innerHeight - 350;
    tabNames = [{ id: 'in', text: '天窗点内上道' }, { id: 'out', text: '天窗点外上道' }]
    tableScroll_cj = { x: '2100px', y: `${this.tableHeight}px` };
    tableScroll_hz = { x: '2100px', y: `${this.tableHeight}px` };

    loading = false;
    statusList = ['未盯控', '正在盯控', '已经完成'];
    needSaveIndexes = new Set();
    timeleft = 300;
    @Output() goBack = new EventEmitter();
    allowTick: boolean;
    isTicking = false;
    showTab2 = true;
    zymList: any = [];
    gqList: any;
    czList: any;
    cjList: any;
    tableWidthConfig_cj = [
        '30px', '35px', '35px', '35px', '35px', '30px', '50px', '55px', '200px',
        '60px', '60px', '70px', '65px', '100px', '50px', '50px', '50px', '50px', '50px',
        '60px',
        '50px', '50px', '100px', '65px', '70px',
        '120px',
    ]
    tableWidthConfig_hz = [
        '35px', '35px', '35px', '35px', '40px', '50px', '55px', '205px',
        '60px', '65px', '70px', '70px', '100px', '50px', '50px', '50px', '50px', '50px',
        '60px',
        '50px', '50px', '100px', '70px', '75px',
        '120px',
        // '100px', '50px', '100px', '100px', '50px', '70px', '200px', '200px',
        // '100px', '100px', '100px', '100px', '150px', '50px', '100px', '100px', '100px', '60px',
        // '200px',
        // '60px', '50px', '150px', '100px', '100px',
        // '100px',
    ]
    nzWidthConfig: string[];
    lockHeadScroll: any = {};
    totalPlanNum = '--';
    needQuery = false;
    handParam: any = {};

    // nzLeft = this.queryParam.uSummary === '1' ? this.tableWidthConfig_hz.slice(0, 8) : this.tableWidthConfig_cj.slice(0, 9);
    // userInfo = JSON.parse(this.ls.get('loginInfo'));
    // isDd = userInfo.

    @Input() set params(param) {
        if (param.uSummary === '1') { // 汇总
            this.getCj();
        } else {
            this.onChangeCj(param._cjId);
        }

        const _queryParam: any = {};
        Object.assign(_queryParam, param);

        this.showTab2 = param.showTab2;
        delete _queryParam.showTab2;
        delete _queryParam._cjId;

        this.tabIndex = 0;
        this.pageIndex = 1;

        this.queryParam = _queryParam;
        this.nzWidthConfig = this.queryParam.uSummary === '1' ? this.tableWidthConfig_hz : this.tableWidthConfig_cj;
        this.initTableScroll();
        this.query(true, 1);
    };

    constructor(
        private http: _HttpClient,
        private datePipe: DatePipe,
        public statusFollowService: StatusFollowService,
        public message: NzMessageService,
        public apiService: ApiService,
        private modalService: NzModalService,
        private exportFile: ExportFileService,
        private ls: LocalStorage,
    ) { }

    ngOnInit() {

    }

    initTableScroll() {
        const scroll = this.queryParam.uSummary === '1' ? this.tableScroll_hz : this.tableScroll_cj;
        Object.assign(this.lockHeadScroll, scroll);
    }

    getZym(row) {
        if (!row.uStation) {
            return;
        }
        this.zymList = [];
        this.getZymList({ stationName: row.uStation }).subscribe(res => {
            for (const item of res.data[0]) {
                if (item) {
                    this.zymList.push(item);
                }
            }
        });
    }

    getTimeLen(date1, date2) {
        if (!date1 || !date2) {
            return;
        }
        const time1 = date1.getTime();
        let time2 = date2.getTime();
        if (time1 > time2) {
            time2 += 24 * 3600 * 1000;
        }
        const time1_m = Math.floor(time1 / 1000 / 60);
        const time2_m = Math.floor(time2 / 1000 / 60);
        return (time2_m - time1_m);
    }

    query(fromBeginning = false, sync = 0) {
        const param = {
            page: fromBeginning === false ? this.pageIndex : 1,
            limit: this.pageSize,
            sync
        };
        const today = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
        this.queryParam.uDwDn = (this.tabNames[this.tabIndex].id === 'in' ? '1' : '0');
        Object.assign(param, this.queryParam);
        this.removePrivateFields(param);
        this.loading = true;
        this.getPlanSta(param);
        this.query_detail(param).subscribe(res => {
            this.loading = false;
            const groupNames = new Set();
            const group = {};
            res.data.forEach(row => {
                groupNames.add(row.uMerge);
                if (group['' + row.uMerge]) {
                    group['' + row.uMerge].push(row);
                } else {
                    group['' + row.uMerge] = [row];
                }
                row._rowspan = 0;
                if (row.uDownSkywintime) {
                    const times = row.uDownSkywintime.split('-');
                    if (times.length === 2) {
                        row._uDownSkywintime1 = new Date(`${today} ${times[0]}`);
                        row._uDownSkywintime2 = new Date(`${today} ${times[1]}`);
                        row._uDownSkywintimeLen = this.getTimeLen(row._uDownSkywintime1, row._uDownSkywintime2);
                    } else {
                        if (row.uDownSkywintime.indexOf('-') === '0') {
                            row._uDownSkywintime2 = new Date(`${today} ${times[0]}`);
                        } else {
                            row._uDownSkywintime1 = new Date(`${today} ${times[0]}`);
                        }
                    }
                }
                row.tcdhsjLen = this.getTimeLen(row._uDownSkywintime1, row._uDownSkywintime2);
                if (row.uUpSkywintime) {
                    const times = row.uUpSkywintime.split('-');
                    row._uUpSkywintime1 = times[0] ? new Date(`${today} ${times[0]}`) : null;
                    row._uUpSkywintime2 = times[1] ? new Date(`${today} ${times[1]}`) : null;
                }
                if (row.uUpTime) {
                    row._uUpTime = new Date(`${today} ${row.uUpTime}`);
                }
                if (row.uDownTime) {
                    row._uDownTime = new Date(`${today} ${row.uDownTime}`);
                }
                if (row.uUpWorkdoor) {
                    row._uUpWorkdoor = row.uUpWorkdoor.split(',');
                }
                if (row.uDownWorkdoor) {
                    row._uDownWorkdoor = row.uDownWorkdoor.split(',');
                }
                if (row.uOutperson) {
                    const rys = row.uOutperson.split(',');
                    if (rys.length && rys[0] === rys[1]) {
                        row.uOutperson = rys[0];
                    }
                }
            });
            const groupNameArr = Array.from(groupNames);
            const tableData = [];
            let rowIndex = 1;
            groupNameArr.forEach((name: any) => {
                const rows = group[name];
                if (rows.some(_row => _row.uStatus === '0')) {
                    rows[0]._groupStatus = '0';
                } else if (rows.some(_row => _row.uStatus === '1')) {
                    rows[0]._groupStatus = '1';
                } else if (rows.every(_row => _row.uStatus === '2')) {
                    rows[0]._groupStatus = '2';
                } else {
                    rows[0]._groupStatus = '0';
                }
                rows[0]._rowspan = rows.length ? rows.length : 0;
                rows[0]._rowIndex = rowIndex;
                rowIndex++;
                tableData.push(...rows);
            });
            // this.totalPlanNum = rowIndex - 1;
            this.tableData = tableData;
            this.pageTotal = res.count;
        });
    }

    getPlanSta(queryParam) {
        const param: any = {};
        Object.assign(param, queryParam);
        delete param.page;
        delete param.limit;
        this.getPlanInfo(param).subscribe(res => {
            if (res.data.length) {
                this.totalPlanNum = res.data[0];
            }
        })
    }

    statusFollow(data) {
        return this.statusFollowService.init('sxdaqkk', data);
    }

    /**
     * 删除私立字段
     * @param param 1
     */
    removePrivateFields(param) {
        Object.keys(param).forEach(key => {
            if ((!(key.indexOf('_')) || !param[key]) && key !== 'uNote') {
                delete param[key];
            }
        });
    }

    noLeaving() {
        return this.isTicking || this.loading
    }

    timeTick(reset?) {
        if (reset) {
            this.timeleft = 300;
        }
        if (this.timeleft === 0) {
            this.saveAll();
            this.isTicking = false;
            return;
        }
        setTimeout(() => {
            this.timeleft--;
            this.timeTick();
        }, 1000);
        this.isTicking = true;
    }

    handSave() {
        if (this.handParam.v) {
            this.onChange(this.handParam.v, this.handParam.data, this.handParam.index, this.handParam.type, 'hand', this.handParam.needQuery);
        } else {
            this.message.success('没有任何修改，无需保存');
        }
    }

    saveAll() {
        const arr = Array.from(this.needSaveIndexes);
        if (!arr.length) {
            this.message.success('没有任何修改，无需保存');
        } else {
            const obs = [];
            arr.forEach((index: any) => {
                const row = this.tableData[index];
                const _r = {};
                Object.assign(_r, row);
                this.beforeSave(_r);
                obs.push(this.update(_r));
            });
            this.loading = true;
            forkJoin(obs).subscribe(resArr => {
                let allres = true;
                resArr.forEach(res => {
                    this.loading = false;
                    if (res.msg === "Ok") {
                        this.message.success('保存成功');
                    } else if (res.msg === 'ERROR') {
                        this.message.warning('保存失败');
                        allres = false;
                    } else {
                        this.message.warning(res.msg);
                    }
                    if (allres && this.needQuery === true) {
                        this.query(false, 0)
                    }
                });
                this.needSaveIndexes.clear();
            })
        }
    }

    beforeSave(row) {
        if (row._uUpSkywintime1) {
            row.uUpSkywintime = this.datePipe.transform(row._uUpSkywintime1, 'HH:mm')
        } else {
            row.uUpSkywintime = '';
        }
        if (row._uUpSkywintime2) {
            row.uUpSkywintime += '-' + this.datePipe.transform(row._uUpSkywintime2, 'HH:mm')
        }

        if (row._uDownSkywintime1) {
            row.uDownSkywintime = this.datePipe.transform(row._uDownSkywintime1, 'HH:mm')
        } else {
            row.uDownSkywintime = '';
        }
        if (row._uDownSkywintime2) {
            row.uDownSkywintime += '-' + this.datePipe.transform(row._uDownSkywintime2, 'HH:mm')
        }
        if (row._uUpTime) {
            row.uUpTime = this.datePipe.transform(row._uUpTime, 'HH:mm')
            if (row.uStatus === '0') {
                row.uStatus = '1';
            }
        } else {
            row.uUpTime = '';
        }
        if (row.uOfficecmd) {
            if (row.uStatus === '0') {
                row.uStatus = '1';
            }
        }
        if (row._uDownTime) {
            row.uDownTime = this.datePipe.transform(row._uDownTime, 'HH:mm')
        } else {
            row.uDownTime = '';
        }
        if (row._uUpWorkdoor) {
            row.uUpWorkdoor = row._uUpWorkdoor.join(',');
        }
        if (row._uDownWorkdoor) {
            row.uDownWorkdoor = row._uDownWorkdoor.join(',');
        }
        this.removePrivateFields(row);
    }

    getChecked() {
        const rows = this.tableData.filter(row => row.checked);
        return rows;
    }

    onRowCheck(v, row) {
        const uMerge = row.uMerge;
        this.tableData.forEach(_row => {
            if (_row.uMerge === uMerge) {
                _row.checked = v;
            }
        });
    }

    queRenAll() {
        let count = 0;
        for (const item of this.tableData) {
            if (item.checked) {
                count++;
            }
        }
        if (count < 1) {
            this.message.error('请选择一条记录');
            return;
        }
        const rows = this.getChecked();
        const ids = [];
        rows.forEach(row => {
            ids.push(row.id);
        });
        // if (!check) {
        //     this.message.error('您只能确认正在盯控的条目');
        //     return;
        // }
        this.modalService.confirm({
            nzTitle: `操作确认`,
            nzWidth: '600',
            nzContent: '确定进行 确认 操作吗?',
            nzOnOk: () => {
                const uId = rows[0].uId;
                const uDate = rows[0].uDate;
                this.queRen({ ids, uId, uDate }).subscribe(res => {
                    if (res.msg === 'Ok') {
                        this.message.success('确认成功');
                        this.query();
                    } else {
                        this.message.success('确认失败');
                    }
                })
            }
        })

    }

    deleteAll() {
        const rows = this.getChecked();
        const ids = [];
        let check = true;
        rows.forEach(row => {
            if (row.uStatus === '2') {
                check = false;
            }
            ids.push(row.id);
        });
        if (!check) {
            this.message.error('您不能删除已经完成的条目');
            return;
        }
        this.modalService.confirm({
            nzTitle: `<i>确认删除</i>`,
            nzWidth: '600',
            nzContent: '确认删除吗?',
            nzOnOk: () => {
                this.delete(ids).subscribe(res => {
                    if (res.msg === 'Ok') {
                        this.message.success('删除成功');
                        this.query();
                    } else if (res.msg === 'ERROR') {
                        this.message.warning('删除失败');
                    } else {
                        this.message.warning(res.msg);
                    }
                })
            }
        })
    }

    goMain() {
        this.goBack.emit();
    }

    tabCHange(v) {
        this.tabIndex = v;
        this.query();
    }

    checkAll(v) {
        this.tableData.forEach(row => {
            row.checked = v;
        });
    }

    onChange(v, data, index, type, saveType, needQuery = false) {
        this.handParam = { 'v': v, 'data': data, 'index': index, 'type': type, 'saveType': '', 'needQuery': needQuery };
        if (this.queryParam.uSummary === '1') {
            return;
        }
        if (type === 'time') {
            this.tableData[index].tcdhsjLen = this.getTimeLen(data._uDownSkywintime1, data._uDownSkywintime2);
        } else {
            this.needQuery = needQuery;
        }
        this.needSaveIndexes.add(index);
        if (saveType === 'hand') {
            this.timeleft = 1;
        } else {
            if (this.isTicking === false) {
                this.timeTick(true);
            } else {
                this.timeleft = 301;
            }
        }
    }

    onTimeClick(v, row, fieldName) {
        if (v === true) {
            setTimeout(() => {
                row[fieldName] = new Date();
            }, 1);
        }
    }

    getCj() {
        this.apiService.getAllChejian('1').subscribe(res => {
            this.cjList = res;
        });
    }
    onChangeCj(v) {
        this.getGq(v);
    }

    getGq(cjId) {
        if (!cjId) {
            return;
        }
        this.apiService.getgongquByCjId(cjId).subscribe(res => {
            this.gqList = res;
        });
    }
    onChangeGq(v) {
        const gqIds = this.gqList.filter(gq => gq.opName === v);
        if (gqIds.length) {
            this.getCz(gqIds[0].opValue);
        }
    }

    getCz(gqId) {
        if (!gqId) {
            return;
        }
        this.apiService.getStationByOrgId(gqId, '1').subscribe(res => {
            this.czList = res;
        });
    }

    changeHeight(type) {
        switch (type) {
            case 'up':
                this.tableHeight -= 200;
                break;
            case 'down':
                this.tableHeight += 200;
                break;
            default:
                break;
        }
        this.lockHeadScroll = { x: '2300px', y: `${this.tableHeight}px` };
    }

    export() {
        let param = '';
        this.queryParam.uDwDn = (this.tabNames[this.tabIndex].id === 'in' ? '1' : '0');
        param += '?uDwDn=' + this.queryParam.uDwDn;
        if (this.queryParam.uSummary) {
            param += '&uSummary' + this.queryParam.uSummary;
        }
        if (this.queryParam.uDate) {
            param += '&uDate' + this.queryParam.uDate;
        }
        if (this.queryParam.uId) {
            param += '&uId' + this.queryParam.uId;
        }
        if (this.queryParam.nWorkshop) {
            param += '&nWorkshop' + this.queryParam.nWorkshop;
        }
        if (this.queryParam.uStatus) {
            param += '&uStatus' + this.queryParam.uStatus;
        }
        if (this.queryParam.uWorkarea) {
            param += '&uWorkarea' + this.queryParam.uWorkarea;
        }
        if (this.queryParam.uStation) {
            param += '&uStation' + this.queryParam.uStation;
        }
        this.exportFile.getDown(environment.project + '/updownRoadd/dataExcel' + param, '车间周计划.xls');
    }


    /**
     * 子表查询
     * @param uSummary 是否是汇总表|0否、1是
     * @param uDwDn 点内还是点外|0天窗点外上道、1天窗点内上道
     * @param page ''
     * @param limit ''
     * @param sync 是否同步数据|0不同步、1同步；同步会占用运行空间，建议行内修改后刷新列表数据不执行同步，进入界面执行同步
     * 以上必传
     * @param uDate 日期|汇总表必须传递主表的日期给此参数，车间表不传|yyyyMM-dd
     * @param uId 主表主键|汇总表此参数不传，车间表传
     * @param uWorkshop 部门车间编号|汇总有此筛选项
     * @param uStatus 状态|0已导入、1已确认
     * @param uWorkarea 工区名称
     * @param uStation 车站名称
     */
    query_detail(param) {
        const dataurl = environment.project + '/updownRoadd/query';
        return this.http.get(dataurl, param);
    }

    /**
     * 修改
     */
    update(param) {
        const dataurl = environment.project + '/updownRoadd/update';
        return this.http.post(dataurl, param);
    }
    /**
     * 作业
     * stationName=珠琳
     * devName=
     */
    getZymList(param) {
        const dataurl = environment.project + '/workdoor/workdoorlist';
        return this.http.get(dataurl, param);
    }

    /**
     * 子表确认
     * @param ids 从表主键集合
     * @param uId 主表主键
     * @param uDate 日期
     */
    queRen(param) {
        const dataurl = environment.project + '/updownRoadd/sureBatch';
        return this.http.post(dataurl, param);
    }

    /**
     * 子表删除
     * @param ids 从表主键集合
     */
    delete(ids) {
        const dataurl = environment.project + '/updownRoadd/deleteBatch';
        return this.http.post(dataurl, { ids });
    }
    /**
     * 子表导出
     * @param uSummary  是否是汇总表|0否、1是
     * @param uDwDn  点内还是点外|0天窗点外上道、1天窗点内上道
     * @param uDate  日期|汇总表必须传递主表的日期给此参数，车间表不传
     * @param uId  主表主键|汇总表此参数不传，车间表传
     * @param nWorkshop  部门车间编号|汇总有此筛选项
     * @param uStatus  状态|0已导入、1已确认
     * @param uWorkarea  工区名称
     * @param uStation  车站名称
     */
    expt(param) {
        const dataurl = environment.project + '/updownRoadd/dataExcel';
        return this.http.get(dataurl, param, { responseType: 'blob', observe: 'response' });
    }

    /**
     * 计划数量
     * @param  uId  1
     * @param  uDwdn  1点内  0点外
     */
    getPlanInfo(param) {
        const dataurl = environment.project + '/updownRoadd/queryPlanSum';
        return this.http.get(dataurl, param);
    }

}
